<?php
	session_start();

/*	XML TEMPLATE FOR CLIENT*/

/*    $xmlGet = "<request>
        <call>getTemplate</call>
        <categoryId>13</categoryId>
        <storeId>2</storeId>
        <productId>2</productId>
        <sku>simple_product</sku>
        <baseUrl>http://192.168.50.3/magento/</baseUrl>
        <newDesign>byte array</newDesign>
    </request>";*/

    $xmlGet     = (!empty($_POST["api_servicecall"]) ? $_POST["api_servicecall"] : NULL);

    $xml        = simplexml_load_string($xmlGet);
    $callGet    = $xml->call;
    $categoryId = $xml->categoryId;
    $_storeId   = $xml->storeId;
    $_productId = $xml->productId;
    $_sku       = $xml->sku;
    $_baseUrl   = $xml->baseUrl;
	$_newDesign	= $xml->newDesign;
	$_newDesignBack	= $xml->newDesignBack;

    switch($callGet){
        case 'getTemplate':
            $customDesign = new CustomDesign($_baseUrl);
            $customDesign->getTemplate($categoryId);
            $customDesign = null;
            break;
        case 'checkout':
            $customDesign = new CustomDesign($_baseUrl);
            $_sessionId = $customDesign->getSessionId();
            $customDesign->checkout($_sessionId,$_storeId,$_productId,$_sku);
			$customDesign->uploadNewDesign($_newDesign,$_newDesignBack);
            $customDesign = null;
		break;
	}

class CustomDesign{
    private $_sessionId = null;
    private $_proxy = null;
    private $_baseUrl = null;
	
    function __construct($_baseUrl){
        $this->_baseUrl = $_baseUrl;
        $this->_proxy = new SoapClient($this->_baseUrl.'index.php/api/v2_soap/?wsdl');
        $this->_sessionId = $this->_proxy->login('Canvas', '1234567890');
    }
    
    public function getSessionId(){
        return $this->_sessionId;
    }

    public function getTemplate($categoryId){
        $xml = new SimpleXMLElement('<response/>');
        $xml->addChild('session_id',$this->_sessionId);
        $arrTemplate = objectToArray($this->_proxy->catalogCategoryAssignedProducts($this->_sessionId,$categoryId));
        foreach($arrTemplate as $key => $value){
            //$kTmpl  = array_keys($arrTemplate[$key]);
            $prodId		= $value['product_id'];
            $prodName 	= null;
            $sku		= null;
            $price		= null;
            $imagePath	= null;
			$_type		= null;

            $arrProd	= objectToArray($this->_proxy->catalogProductInfo($this->_sessionId, $prodId));
            $prodName 	= $arrProd['name'];
            $sku		= $arrProd['sku'];
            $price		= $arrProd['price'];
			$_type		= $arrProd['type'];
			
			if ($_type == 'virtual'){
                if(empty($_SESSION['regVirtualProductId'])){
                    session_register("regVirtualProductId");
					$_SESSION['regVirtualProductId']  = $prodId;
                }
				if(empty($_SESSION['regSKU'])){
					session_register("regSKU");
                    $_SESSION['regSKU']  = $sku;
                }
				else{
					$_SESSION['regSKU']  = $sku;
				}
			}	
			else{
			$arrProd	= objectToArray($this->_proxy->catalogProductInfo($this->_sessionId, $prodId));
            $prodName 	= $arrProd['name'];
            $sku		= $arrProd['sku'];
	            $arrImg = objectToArray($this->_proxy->catalogProductAttributeMediaList($this->_sessionId, $prodId));
	            foreach($arrImg as $keyImg => $valueImg){
	                $imagePath = $valueImg['url'];
	            }
	            $background = $xml->addChild('background');
	            $background->addChild('product_id',$prodId);
	            $background->addChild('product_name',$prodName);
	            $background->addChild('sku',$sku);
	            $background->addChild('price',$price);
	            $background->addChild('image_path',$imagePath);
				$background->addChild('product_type',$_type);
			}
        }
		
		$_themesRootId = 16;
		$result = objectToArray($this->_proxy->catalogCategoryTree($this->_sessionId,$_themesRootId));
		//print_r($result['children']);
		$_themes = $xml->addChild('themes');
		foreach($result['children'] as $_theme){
			$_shapes = $_themes->addChild('theme_name',$_theme['name']);
			$_arrShapes = objectToArray($this->_proxy->catalogCategoryAssignedProducts($this->_sessionId,$_theme['category_id']));
			foreach ($_arrShapes as $key => $_shape){
				$_shapeInfo	= objectToArray($this->_proxy->catalogProductInfo($this->_sessionId, $_shape['product_id']));
/*	            $_shapeName	= $_shapeInfo['name'];
	            $_shapeSKU	= $_shapeInfo['sku'];*/
	            
				$_shapeImages = objectToArray($this->_proxy->catalogProductAttributeMediaList($this->_sessionId, $_shape['product_id']));
	            foreach($_shapeImages as $keyImg => $_shapeImage){
	                $_shapeImagePath = $_shapeImage['url'];
	            }
				
				$_shapes->addChild('shape_name',$_shapeInfo['name']);
				$_shapes->addChild('shape_sku',$_shapeInfo['sku']);
				$_shapes->addChild('shape_image',$_shapeImagePath);
			}
		}
		
        $doc = new DOMDocument('1.0');
        $doc->preserveWhiteSpace = false;
        $doc->loadXML( $xml->asXML() );
        $doc->formatOutput = true;
        header('Content-Type: application/xml');
        print($doc->saveXML());
    }

    public function checkout($_sessionId,$_storeId,$_productId,$_sku){
		if ($_productId == 0 || $_productId == '0' ){
			if(!empty($_SESSION['regVirtualProductId'])){
				$_productId = $_SESSION['regVirtualProductId'];
			}
			if(!empty($_SESSION['regSKU'])){
				$_sku = $_SESSION['regSKU'];
			}
		}
        
		$_cartId = $this->_proxy->shoppingCartCreate($_sessionId, $_storeId);
        $_cartAdd = $this->_proxy->shoppingCartProductAdd($_sessionId, $_cartId, array(array(
            'product_id' => $_productId,
            'sku' => $_sku,
            'qty' => '1',
            'options' => null,
            'bundle_option' => null,
            'bundle_option_qty' => null,
            'links' => null
        )));
		
/*		if(empty($_SESSION['addFrontFile'])){
        	session_register('addFrontFile');    
			$_SESSION['addFrontFile'] = $this->_baseUrl.'media/newdesign/'.$this->_sessionId.'_front.jpg';
        }
		else{
			$_SESSION['addFrontFile'] = $this->_baseUrl.'media/newdesign/'.$this->_sessionId.'_front.jpg';
		}*/
		
		$this->_sessionId = $_sessionId;

        if ($_cartAdd){
            $_headerLocation = $this->_baseUrl.'checkout/cart/add/uenc/'.$_sessionId.'/product/'.$_productId.'/canvas/1/image/'.$this->_sessionId.'_front.jpg';
            $xml = new SimpleXMLElement('<response/>');
            $xml->addChild('headerLocation',$_headerLocation);
            $doc = new DOMDocument('1.0');
            $doc->preserveWhiteSpace = false;
            $doc->loadXML( $xml->asXML() );
            $doc->formatOutput = true;
            header('Content-Type: application/xml');
            print($doc->saveXML());
        }
    }
	
	public function uploadNewDesign($_fileFront,$_fileBack){
		/*$arrFiles = array();*/
		// base64 encoded utf-8 string

		$_binaryFront = base64_decode($_fileFront);
		header('Content-Type: image/jpg; charset=utf-8');
		$_fileFront = fopen('./media/newdesign/'.$this->_sessionId.'_front.jpg', 'wb');
		fwrite($_fileFront, $_binaryFront);
		fclose($_fileFront);
		
		$_binaryBack = base64_decode($_fileBack);
		header('Content-Type: image/jpg; charset=utf-8');
		$_fileBack = fopen('./media/newdesign/'.$this->_sessionId.'_back.jpg', 'wb');
		fwrite($_fileBack, $_binaryBack);
		fclose($_fileBack);
	}
}

function objectToArray($d) {
    if (is_object($d)) {
            $d = get_object_vars($d);
    }
    if (is_array($d)) {
            return array_map(__FUNCTION__, $d);
    }
    else {
            return $d;
    }
}
?>